"""
FileName：db_client.py
Description：
Author：gaojiahui
Time：2025/8/18 20:09
Website：https://gitee.com/gao-jiahui
"""
import pymysql
import pymysql.cursors

from config.settings import settings
from core.exceptions import DatabaseError
from core.logger import logger


class DBClient:
    def __init__(self):
        self.connection = None
        self.connect()

    def connect(self):
        """连接数据库"""
        try:
            self.connection = pymysql.connect(
                autocommit=True,    # 自动提交
                host=settings.DB_HOST,
                port=settings.DB_PORT,
                user=settings.DB_USER,
                password=settings.DB_PASSWORD,
                database=settings.DB_NAME,
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            logger.info("数据库连接成功")
        except pymysql.Error as e:
            logger.error(f"数据库连接失败: {str(e)}")
            raise DatabaseError(f"数据库连接失败: {str(e)}")

    def execute_query(self, sql: str, params=None):
        """执行查询语句"""
        try:
            with self.connection.cursor() as cursor:
                cursor.execute(sql, params or ())
                return cursor.fetchall()
        except pymysql.Error as e:
            logger.error(f"查询执行失败: SQL: {sql}, 参数: {params}, 错误: {str(e)}")
            raise DatabaseError(f"查询失败: {str(e)}")

    def execute_update(self, sql: str, params=None):
        """执行更新语句"""
        try:
            with self.connection.cursor() as cursor:
                affected_rows = cursor.execute(sql, params or ())
                self.connection.commit()
                return affected_rows
        except pymysql.Error as e:
            self.connection.rollback()
            logger.error(f"更新执行失败: {str(e)}")
            raise DatabaseError(f"更新失败: {str(e)}")

    def close(self):
        """关闭数据库连接"""
        if self.connection:
            self.connection.close()
            logger.info("数据库连接已关闭")
